package com.auto.survey.activity.monitoring.adapter

import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.Adapter
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.auto.survey.R
import com.auto.survey.activity.monitoring.entity.MonitoringPoint
import com.auto.survey.util.Helper

class MontoringPointAdapter(needChoice:Boolean = false, private val recyclerView: RecyclerView) : Adapter<MontoringPointAdapter.MontoringPointAdapterViewHodler>() {

    private val checkVisible = needChoice

    private var isGoneDelteAndUpdate = false

    private var mItemClickListener:OnPointClickItemListener?= null

    private var mDeleteClickListener:OnPointDeleteClickListener?= null

    private var mUpdateClickListener:OnPointUpdateClickListener?=null

    private var mItems :List<MonitoringPoint> = mutableListOf()

    // 当前选中项的位置，初始为-1表示未选中
    private var selectedPosition = -1

    fun setData(items:List<MonitoringPoint>) {
        mItems = items
        notifyDataSetChanged()
    }

    fun setGoneDelteAndUpdate(isGone:Boolean) {
        isGoneDelteAndUpdate = isGone
        notifyDataSetChanged()
    }

    fun setOnItemClickListener (onItemClickListener:OnPointClickItemListener) {
        mItemClickListener = onItemClickListener
    }

    fun setOnDeleteClickListener(listener:OnPointDeleteClickListener) {
        mDeleteClickListener = listener
    }

    fun setOnUpdateClickListener(listener:OnPointUpdateClickListener) {
        mUpdateClickListener = listener
    }

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): MontoringPointAdapterViewHodler {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_monroting_point,parent, false)
        return MontoringPointAdapterViewHodler(view)
    }

    override fun getItemCount(): Int {
        if (mItems.isNotEmpty()) {
            return mItems.size
        }
        return 0
    }

    override fun onBindViewHolder(holder: MontoringPointAdapterViewHodler, position: Int) {

        //测点名称

        val pName = mItems[position].pointName
        val pType = mItems[position].pointType

        if (TextUtils.isEmpty(pType)) {
            holder.tv_monroting_point_name.text= pName
        } else{
            val content = "$pName($pType)"
            holder.tv_monroting_point_name.text = content
        }

        if (TextUtils.isEmpty(mItems[position].pointName)) {
            holder.tv_monroting_point_name.text= ""
        }

        // 水平角（使用角度转换）
        setTextIfNotNull(holder.tv_monroting_point_hz, mItems[position].pointHz) {
            Helper.radiansToDMSString(it)
        }

        // 竖直角（使用角度转换）
        setTextIfNotNull(holder.tv_monroting_point_va, mItems[position].pointV) {
            Helper.radiansToDMSString(it)
        }

        // 斜距（使用小数格式化）
        setTextIfNotNull(holder.tv_monroting_point_sd, mItems[position].pointSD) {
            Helper.formateDecimal(it).toString()
        }


        //棱镜高
        holder.tv_monroting_point_mh.text= mItems[position].mirrorHeight.toString()

        //x
        if (mItems[position].pointX == 0.0) {
            holder.tv_monroting_point_xn.text = ""
        } else {
            holder.tv_monroting_point_xn.text=mItems[position].pointX.toString()
        }

        //y
        if (mItems[position].pointY == 0.0) {
            holder.tv_monroting_point_ye.text = ""
        } else {
            holder.tv_monroting_point_ye.text=mItems[position].pointY.toString()
        }

        //z
        if (mItems[position].pointZ == 0.0) {
            holder.tv_monroting_point_zh.text = ""
        } else {
            holder.tv_monroting_point_zh.text=mItems[position].pointZ.toString()
        }


        if (checkVisible) {

            val isSelected = position == selectedPosition
            holder.tv_update.visibility = View.GONE
            holder.tv_delete.visibility = View.GONE
            holder.checkbox.visibility = View.VISIBLE
            holder.tv_mirror.visibility = View.VISIBLE
            // 移除旧的监听器，避免重复触发
            holder.checkbox.setOnCheckedChangeListener(null)

            // 防止ViewHolder复用导致的状态错乱，强制设置CheckBox状态
            holder.checkbox.isChecked = isSelected

            holder.checkbox.setOnCheckedChangeListener { buttonView, isChecked ->
                if (isChecked) {

                    if (position != selectedPosition) {
                        Log.i("MontoringPointAdapter", "==MontoringPointAdapter==checkbox===OnCheckedChangeListener ###position=$position")
                        selectItem(position)
                    }

                } else  {
                    // 如果取消选中当前项（可选功能）
                    if (selectedPosition == position) {
                        selectedPosition = -1
                        notifyItemChanged(position) // 刷新当前项，确保UI同步
                    }
                }
            }

            holder.root.setOnClickListener {
                Log.i("MontoringPointAdapter", "==MontoringPointAdapter==checkVisible=$checkVisible, position = $position")
                selectItem(position)
            }
        } else {
            holder.checkbox.visibility = View.GONE
            holder.tv_mirror.visibility = View.GONE
            holder.tv_update.visibility = View.VISIBLE
            holder.tv_delete.visibility = View.VISIBLE

            holder.tv_delete.setOnClickListener {
                mDeleteClickListener?.onDelteClick(mItems[position], position)
            }

            holder.tv_update.setOnClickListener {
                mUpdateClickListener?.onUpdateClick(mItems[position], position)
            }

            holder.root.setOnClickListener {
                // 通知点击事件
                Log.i("MontoringPointAdapter", "==MontoringPointAdapter==checkVisible=$checkVisible, onclick ")
                mItemClickListener?.ontItemPointClick(mItems[position], position)
            }

        }

        if (isGoneDelteAndUpdate) {
            holder.tv_update.visibility = View.GONE
            holder.tv_delete.visibility = View.GONE
        }

    }

    // 选中指定位置的item
    private fun selectItem(position: Int) {
        Log.i("MontoringPointAdapter", "==MontoringPointAdapter==selectItem ##position=$position, selectedPosition = $selectedPosition")
        if (position == selectedPosition) return

        val previousSelected = selectedPosition
        selectedPosition = position

        recyclerView.post {
            // 更新上一个选中项
            if (previousSelected != -1 && previousSelected < mItems.size) {
                Log.i("MontoringPointAdapter", "==MontoringPointAdapter==recyclerView post ##previousSelected=$previousSelected")
                notifyItemChanged(previousSelected)
            }
            // 更新当前选中项
            notifyItemChanged(position)

        }

        // 通知点击事件
        mItemClickListener?.ontItemPointClick(mItems[position], position)
    }

    // 提取通用函数：处理可空值并设置文本（支持自定义转换）
    private fun <T> setTextIfNotNull(view: TextView, value: T?, transform: (T) -> String) {
        view.text = value?.let(transform) ?: ""
    }


    class MontoringPointAdapterViewHodler(itemview:View):ViewHolder(itemview) {

        val root = itemview.findViewById<ConstraintLayout>(R.id.cl_monroting_point)
        val checkbox = itemview.findViewById<CheckBox>(R.id.cb_monroting_point)

        val tv_monroting_point_name = itemview.findViewById<TextView>(R.id.tv_monroting_point_name)

        val tv_monroting_point_hz = itemview.findViewById<TextView>(R.id.tv_monroting_point_hz)
        val tv_monroting_point_va = itemview.findViewById<TextView>(R.id.tv_monroting_point_va)
        val tv_monroting_point_sd = itemview.findViewById<TextView>(R.id.tv_monroting_point_sd)
        val tv_monroting_point_mh = itemview.findViewById<TextView>(R.id.tv_monroting_point_mh)

        val tv_monroting_point_xn = itemview.findViewById<TextView>(R.id.tv_monroting_point_xn)
        val tv_monroting_point_ye = itemview.findViewById<TextView>(R.id.tv_monroting_point_ye)
        val tv_monroting_point_zh = itemview.findViewById<TextView>(R.id.tv_monroting_point_zh)

        val tv_update = itemview.findViewById<TextView>(R.id.tv_monroting_point_update)
        val tv_delete = itemview.findViewById<TextView>(R.id.tv_monroting_point_delete)

        val tv_mirror = itemview.findViewById<TextView>(R.id.tv_monroting_point_mirror)

    }

    interface OnPointClickItemListener {
        fun ontItemPointClick(point:MonitoringPoint, selectedPosition:Int)
    }

    interface OnPointDeleteClickListener {
        fun onDelteClick(point:MonitoringPoint, deletePosition:Int)
    }


    interface OnPointUpdateClickListener {
        fun onUpdateClick(point:MonitoringPoint, updatePosition:Int)
    }
}